﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RemoteData.core.queue
{
    public class Worker
    {
        private static ILog logger = LogManager.GetLogger(typeof(Worker));

        public bool stopFlag = true;

        public Thread thWorker = null;
        public DateTime startTime;

        public Worker() { }

        public void StartAsync()
        {
            thWorker = new Thread(new ThreadStart(() => Start()));
            thWorker.Start();
        }

        public virtual void Start()
        {

        }

        protected virtual int PreStart()
        {
            return 0;
        }

        protected virtual int AfterStart()
        {
            return 0;
        }

        public virtual void Stop()
        {
            this.stopFlag = true;
        }

        public bool IsStop()
        {
            return stopFlag;
        }

        /// <summary>
        /// 等待线程正常结束
        /// </summary>
        public void Join()
        {
            try
            {
                thWorker.Join();
            }
            catch (Exception)
            {
                string errMsg = string.Format("worker {0} Join操作异常", thWorker.ManagedThreadId);
                logger.ErrorFormat(errMsg);
            }
        }

        public bool Join(int milliSeconds)
        {
            bool flag = true;
            if (thWorker != null)
            {
                try
                {
                    flag = thWorker.Join(milliSeconds);
                }
                catch (Exception)
                {
                    string errMsg = string.Format("worker {0} Join操作异常", thWorker.ManagedThreadId);
                    logger.ErrorFormat(errMsg);
                }
            }
            return flag;
        }
    }
}
